﻿using QAU.DFS.Model;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;

namespace QAU.DFS.Web.Controllers
{
    public class HomeController : Controller
    {
        //
        // GET: /Home/
        ImageServerEntities db = new ImageServerEntities();
        public ActionResult Index()
        {
            return View();
        }

        public ActionResult FileUp()
        {
            
            HttpPostedFileBase file = Request.Files["fileUp"];
            string fileName = Path.GetFileName(file.FileName);
            string fileExt = Path.GetExtension(fileName);
            if (string.Equals(fileExt,".png",StringComparison.OrdinalIgnoreCase)==true || 
                string.Equals(fileExt, ".jpg", StringComparison.OrdinalIgnoreCase) ==true)
            {
                //从服务器状态表筛选出可用的图片服务器集合记作C，并获取集合的总记录数N，然后用随机函数产生一个随机数R1，并用R1与N进行取余运算记作I=R1%N。 则C[I]即为要保存图片的图片服务器 
                
                List<ImageServerInfo> list = db.ImageServerInfo.Where(c => c.FlgUsable == true).ToList();
                int count = list.Count();
                Random random = new Random();
                int r = random.Next();
                int i = r % count;
                ImageServerInfo imageService = list[i];
                string url = imageService.ServerUrl;//图片服务器的地址
                int serverId = imageService.ServerId;//图片服务器编号
                string address = "http://"+url+"/FileUp.ashx?serverId="+serverId+"&ext="+fileExt;

                WebClient client = new WebClient();
                client.UploadData(address, StreamToByte(file.InputStream));
                
            }
            return Content("ok");
            
        }
        private byte[] StreamToByte(Stream stream)
        {
            byte[] buffer = new byte[stream.Length];
            stream.Read(buffer, 0, buffer.Length);
            stream.Seek(0, SeekOrigin.Begin);
            return buffer;
        }

        public ActionResult ShowImage()
        {
            var imageServerInfo = db.ImageServerInfo.Where(c => c.FlgUsable == true).ToList();
            ViewData["imageServerList"] = imageServerInfo;
            return View();
        }

    }
}
